// app-optimizer.js
import { useAppStore } from '@/store'
import { createPinia } from 'pinia'

// 添加过渡动画
const addTransitionEffects = () => {
  const applyEffects = () => {
    // 页面切换动画
    const mainContent = document.querySelector('.app-main')
    if (mainContent) {
      mainContent.style.opacity = '0'
      setTimeout(() => {
        mainContent.style.transition = 'opacity 0.5s ease-in-out'
        mainContent.style.opacity = '1'
      }, 100)
    }

    // 侧边栏切换动画优化
    const sidebar = document.querySelector('.app-sidebar')
    if (sidebar) {
      sidebar.style.transition = 'width 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', applyEffects)
  } else {
    setTimeout(applyEffects, 0)
  }
}

// 优化应用启动速度
const optimizeStartup = () => {
  const loadNonCriticalResources = () => {
    setTimeout(() => {
      // 预加载其他页面组件
      import('@/views/About.vue')
      import('@/views/Settings.vue')
    }, 1000)
  }

  if (document.readyState === 'complete') {
    loadNonCriticalResources()
  } else {
    window.addEventListener('load', loadNonCriticalResources)
  }
}

// 添加键盘快捷键
const setupKeyboardShortcuts = (router) => {
  const handleKeyDown = (e) => {
    // 使用对象映射简化快捷键判断
    const shortcuts = {
      ',': () => router.push('/settings'),
      'h': () => router.push('/'),
      'i': () => router.push('/about')
    }

    if (e.ctrlKey && shortcuts[e.key]) {
      shortcuts[e.key]()
    }
  }

  window.addEventListener('keydown', handleKeyDown)
}

// 优化交互体验
const enhanceInteraction = () => {
  // 添加触摸支持（被动事件监听器）
  document.addEventListener('touchstart', () => {}, { passive: true })
  
  // 优化按钮点击反馈（使用事件委托提高性能）
  document.addEventListener('click', (e) => {
    if (e.target.tagName === 'BUTTON') {
      e.target.style.transform = 'scale(0.95)'
      setTimeout(() => {
        e.target.style.transform = 'scale(1)'
      }, 100)
    }
  })
}

export default {
  install(app, { router }) {
    // 1. 创建并注册Pinia实例
    const pinia = createPinia()
    app.use(pinia)
    
    // 2. 初始化应用存储
    const store = useAppStore()
    store.initSystemInfo()
    
    // 应用启动后执行优化
    app.mixin({
      mounted() {
        if (!this.$parent) {  // 根组件判断
          addTransitionEffects()
          optimizeStartup()
          if (router) {
            setupKeyboardShortcuts(router)
          }
          enhanceInteraction()
        }
      }
    })
    
    // 添加全局属性
    app.config.globalProperties.$optimizeUI = {
      addTransitionEffects,
      optimizeStartup,
      setupKeyboardShortcuts: (router) => setupKeyboardShortcuts(router),
      enhanceInteraction
    }
  }
}
